import { defineStore } from 'pinia'

export const usePermissionStore = defineStore('permission', {
  state: () => ({
    ACCESS_FINE_LOCATION: false,
    READ_EXTERNAL_STORAGE: false,
    CALL_PHONE: false,
    CAMERA: false,
    isIos: false, // 初始为 false，后续初始化
    mapping: {
      ACCESS_FINE_LOCATION: {
        title: "地理位置权限说明",
        content: "获取您的位置为您提供更多的商品信息，获取收货地址能为您提供更好的服务",
        methods: "SET_ACCESS_FINE_LOCATION",
      },
      READ_EXTERNAL_STORAGE: {
        title: "存储空间/照片权限说明",
        content: "便于您使用该功能上传照片/图片/视频，在与客服沟通等场景中读取和写入相册和文件内容",
        methods: "SET_READ_EXTERNAL_STORAGE",
      },
      CALL_PHONE: {
        title: "拨打/管理电话权限说明",
        content: "便于您使用该功能联系商家或者商家与您联系等场景",
        methods: "SET_CALL_PHONE",
      },
      CAMERA: {
        title: "拍照权限说明",
        content: "便于您使用该功能扫描商品条码，在客诉申请、订单评价、地推陈列商品展示等场景时拍摄照片",
        methods: "SET_CAMERA",
      },
    },
  }),
  actions: {
    // 初始化 iOS 标识（仅 App 端执行）
    initIsIos() {
      /* #ifdef APP-PLUS */
      this.isIos = plus.os.name === "iOS";
      /* #endif */
    },

    // 权限申请主方法
    async requestPermissions(permissionID) {
      try {
        /* #ifdef APP-PLUS */
        if (!this[permissionID] && !this.isIos) {
          const viewObj = await this.nativeObjView(permissionID);
          setTimeout(() => {
            viewObj.show()
          }, 100)
        }
        console.log("android.permission." + permissionID, "当前手机权限");
        /* #endif */

        return new Promise(async (resolve) => {
          /* #ifdef MP-WEIXIN */
          resolve(1);
          return;
          /* #endif */

          // iOS 权限分支
          if (this.isIos) {
            async function getPermisson(permisson) {
              switch (permisson) {
                case "CAMERA":
                  return await this.judgeIosPermissionCamera();
                case "ACCESS_FINE_LOCATION":
                  return await this.judgeIosPermissionLocation();
                case "READ_EXTERNAL_STORAGE":
                  return await this.judgeIosPermissionPhotoLibrary();
                default:
                  return false;
              }
            }
            const jurisdictionType = await getPermisson.call(this, permissionID);
            if (jurisdictionType) {
              resolve(1);
            } else {
              // 不同权限的弹窗引导
              const modalConfig = {
                CAMERA: {
                  title: "允许“悦合集”使用摄像头？",
                  content: "请在设置中开启摄像头权限，用于拍照、扫描商品条码等",
                },
                ACCESS_FINE_LOCATION: {
                  title: "允许“悦合集”使用你的位置？",
                  content: "请在设置中开启位置权限，用于获取您的位置为您提供更多的商品信息，获取收货地址能为您提供更好的服务",
                },
                READ_EXTERNAL_STORAGE: {
                  title: "允许“悦合集”使用你的相册？",
                  content: "请在设置中开启相册权限，用于您使用该功能上传照片/图片/视频，在与客服沟通等场景中读取和写入相册和文件内容",
                },
              };
              const { title, content } = modalConfig[permissionID] || {};
              if (title && content) {
                uni.showModal({
                  title,
                  content,
                  confirmText: "去设置",
                  success: (res) => {
                    res.confirm && this.gotoAppPermissionSetting();
                  },
                });
              }
            }
            return;
          }

          // Android 权限申请
          function requestAndroidPermission(permissionID_) {
            return new Promise((resolve) => {
              plus.android.requestPermissions(
                [permissionID_],
                (resultObj) => {
                  let result = 0;
                  if (resultObj.granted.length > 0) result = 1; // 已授权
                  else if (resultObj.deniedPresent.length > 0) result = 0; // 本次拒绝
                  else if (resultObj.deniedAlways.length > 0) result = -1; // 永久拒绝
                  resolve(result);
                },
                (error) => {
                  console.log("申请权限错误：", error);
                  resolve({ code: error.code, message: error.message });
                }
              );
            });
          }

          const result = await requestAndroidPermission(
            "android.permission." + permissionID
          );
          // 直接修改 state（Pinia 支持 actions 中直接赋值）
          if (result === 1) this[permissionID] = true;
          else this[permissionID] = false;

          // 永久拒绝时引导去设置
          if (result === -1) {
            uni.showModal({
              title: "提示",
              content: "操作权限已被拒绝，请手动前往设置",
              confirmText: "立即设置",
              success: (res) => {
                res.confirm && this.gotoAppPermissionSetting();
              },
            });
          }

          viewObj && viewObj.close();
          resolve(result);
        });
      } catch (error) {
        console.log("权限申请异常：", error);
      }
    },

    // 生成原生提示框（权限引导）
    nativeObjView(permissionID) {
      const systemInfo = uni.getSystemInfoSync();
      const statusBarHeight = systemInfo.statusBarHeight;
      const navigationBarHeight = systemInfo.platform === "android" ? 48 : 44;
      const totalHeight = statusBarHeight + navigationBarHeight;

      let view = new plus.nativeObj.View("per-modal", {
        top: "0px",
        left: "0px",
        width: "100%",
        backgroundColor: "#444",
      });
      view.drawRect({ color: "#fff", radius: "5px" }, {
        top: totalHeight + "px",
        left: "5%",
        width: "90%",
        height: "100px",
      });
      view.drawText(
        this.mapping[permissionID].title,
        { top: totalHeight + 5 + "px", left: "8%", height: "30px" },
        { align: "left", color: "#000" },
        { onClick: (e) => console.log(e) }
      );
      view.drawText(
        this.mapping[permissionID].content,
        { top: totalHeight + 35 + "px", left: "8%", width: "84%", height: "60px" },
        { whiteSpace: "normal", size: "14px", align: "left", color: "#656563" }
      );

      return {
        show: () => {
          view = plus.nativeObj.View.getViewById("per-modal");
          view.show();
          view = null;
        },
        close: () => {
          view = plus.nativeObj.View.getViewById("per-modal");
          view.close();
          view = null;
        },
      };
    },

    // 跳转系统权限设置页
    gotoAppPermissionSetting() {
      if (this.isIos) {
        const UIApplication = plus.ios.import("UIApplication");
        const application2 = UIApplication.sharedApplication();
        const NSURL2 = plus.ios.import("NSURL");
        const setting2 = NSURL2.URLWithString("app-settings:");
        application2.openURL(setting2);
        plus.ios.deleteObject(setting2);
        plus.ios.deleteObject(NSURL2);
        plus.ios.deleteObject(application2);
      } else {
        const Intent = plus.android.importClass("android.content.Intent");
        const Settings = plus.android.importClass("android.provider.Settings");
        const Uri = plus.android.importClass("android.net.Uri");
        const mainActivity = plus.android.runtimeMainActivity();
        const intent = new Intent();
        intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        const uri = Uri.fromParts("package", mainActivity.getPackageName(), null);
        intent.setData(uri);
        mainActivity.startActivity(intent);
      }
    },

    // iOS 相机权限判断
    judgeIosPermissionCamera() {
      return new Promise((resolve) => {
        const AVCaptureDevice = plus.ios.import("AVCaptureDevice");
        const authStatus = AVCaptureDevice.authorizationStatusForMediaType('vide');
        resolve(authStatus === 3 || authStatus === 0); // 已授权/未请求过
        plus.ios.deleteObject(AVCaptureDevice);
      });
    },

    // iOS 定位权限判断
    judgeIosPermissionLocation() {
      return new Promise((resolve) => {
        const CLLocationManager = plus.ios.import("CLLocationManager");
        const status = CLLocationManager.authorizationStatus();
        resolve(status !== 2); // 非“拒绝”状态则认为有效
        plus.ios.deleteObject(CLLocationManager);
      });
    },

    // iOS 相册权限判断
    judgeIosPermissionPhotoLibrary() {
      return new Promise((resolve) => {
        const PHPhotoLibrary = plus.ios.import("PHPhotoLibrary");
        const authStatus = PHPhotoLibrary.authorizationStatus();
        resolve(authStatus === 3 || authStatus === 0); // 已授权/未请求过
        plus.ios.deleteObject(PHPhotoLibrary);
      });
    },
  },
});
